/**
 * Created by zhangyida on 15/12/29.
 */
'use strict';

import {
    View,
    TouchableOpacity,
    Navigator,
    Text,
    StyleSheet,
    Image,
    ListView,
    Animated,
    Easing,
    Modal,
    SegmentedControlIOS,
    TouchableHighlight,
    AlertIOS,
    ActivityIndicatorIOS
} from 'react-native';
import React from 'react';
import URL from '../config/server';
import {Utils} from '../config/utils';
import {Key} from '../config/key';
import Footer from '../component/Footer';
import ScrollNews from '../component/ScrollNews';
import Icon from 'react-native-vector-icons/Ionicons';

function formatDate2(date) {
    return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
}

function isSameDay(date1, date2 = new Date()) {
    return formatDate2(date1) == formatDate2(date2)
}
function formateDate3(str) {
    str = str.replace(/-/g, "/");
    let date = new Date(str);
    return date;
}
var DATATYPE = 1;
const navigationBar = (
    <Navigator.NavigationBar
        style={{backgroundColor: '#e02820', alignItems: 'center'}}
        routeMapper={{
                    LeftButton(route, navigator, index, navState) {
                        return (
                            <TouchableOpacity style={{flex: 1, justifyContent: 'center',paddingLeft:10}}
                                              onPress={() => navigator.parentNavigator.pop()}>
                                <View style={{flexDirection:'row',padding:5}}>
                                    <Icon name="ios-arrow-back" size={18} color="#ffffff" style={{alignSelf:'center'}}/>
                                    <Text style={{color: 'white', margin: 3,fontSize:16}}>
                                        返回
                                    </Text>
                                </View>
                            </TouchableOpacity>
                        );
                    },
                    RightButton(route, navigator, index, navState) {
                        return (
                            <Search navigator={navigator}/>
                        );
                    },
                    _onValueChange: function (value, navigator) {
                        if(value=='狙击涨停'){
                            DATATYPE=1
                        }else{
                            DATATYPE=2
                        }

                        navigator.parentNavigator.replace({
                            id:'Mrzt',
                            message:navigator.props.message
                        })
                    },
                    Title(route, navigator, index, navState) {
                        return (
                            <View style={{alignItems:'center',justifyContent:'center'}}>
                                <SegmentedControlIOS
                                    navigator={navigator}
                                    style={styles.newstitle}
                                    tintColor="#ffffff"
                                    selectedIndex={DATATYPE==1?0:1}
                                    onValueChange={(value)=>{this._onValueChange(value,navigator)}}
                                    values={['狙击涨停', '蓄势待发']}/>
                            </View>
                        );
                    }
            }}
    />
);
class Search extends React.Component {
    _toSeach() {
        this.props.navigator.parentNavigator.push({
            id: 'MrztSearch',
            message: DATATYPE,
            sceneConfig: Navigator.SceneConfigs.FloatFromBottom
        })
    }

    render() {
        return (
            <TouchableOpacity onPress={this._toSeach.bind(this)} underColor="#e02820" style={styles.search}>
                <Icon name="ios-search" size={26} color="#ffffff"/>
            </TouchableOpacity>
        );
    }
}

export default class Mrzt extends React.Component {

    constructor(props) {
        super(props);
        console.log(this.props);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2
            }),
            loaded: 0,
            loadMore: true,
            pagesize: 20,
            showDate: this.props.message.showDate == null ? new Date() : formateDate3(this.props.message.showDate),
            angle: new Animated.Value(0),
            scroll: '',
            isRed: true,
            modalVisiable: false
        };
    }

    componentWillMount() {
        this.fetchData();
        this.fetchScroll();
        this.MrztTimer = setInterval(()=> {
            this.fetchData();
        }, 10000)
    }

    componentWillUnmount() {
        clearInterval(this.MrztTimer);
        console.log('compononte unmoungt!!!');
    }

    _forwardDay() {
        console.log(this.state.showDate.getDate());
        let oldDay = this.state.showDate;
        let newDate = new Date((oldDay / 1000 - 86400) * 1000);
        if (isSameDay(newDate)) {
            this.setState({
                showDate: newDate,
                isRed: true,
            });
        } else {
            this.setState({
                showDate: newDate,
                isRed: false
            });
        }
        this.fetchData();
    }

    _backwardDay() {
        console.log(this.state.showDate.getDate());
        let oldDay = this.state.showDate;
        let newDate = new Date((oldDay / 1000 + 86400) * 1000);
        if (isSameDay(newDate)) {
            this.setState({
                showDate: newDate,
                isRed: true
            });
        } else {
            this.setState({
                showDate: newDate,
                isRed: false
            });
        }
        this.fetchData();
    }

    _refresh() {
        var TIMES = 1;
        this.state.angle.setValue(0);
        this._anim = Animated.timing(this.state.angle, {
            toValue: 360 * TIMES,
            duration: 800 * TIMES,
            easing: Easing.linear
        }).start(this._animate);
        this.fetchData();
    }

    fetchScroll() {
        let that = this;
        const SCROLL = URL.local + 'roll';
        Utils.get(SCROLL, function (data) {
            that.setState({
                scroll: data.content
            })
        })
    }

    fetchData() {
        var that = this;
        this.triggerModal();
        if (!this._isFetching) {

            this._isFetching = true;//用于方式不断的调用

            //这里配置调用后台的url
            var API_URL = URL.local + 'daily/';
            var PARAMS = DATATYPE + '/1/' + this.state.pagesize + '?date=' + formatDate2(this.state.showDate);
            var REQUEST_URL = API_URL + PARAMS;
            Utils.transport(REQUEST_URL, '', function (responseData) {
                console.log(responseData);
                if (responseData == -1) {
                    AlertIOS.alert(
                        '您的权限不够',
                        '请您升级权限, 或等到休市之后再来访问.',
                        [
                            {
                                text: '去升级', onPress: () => {
                                if (Key.username == '') {
                                    that.props.navigator.push({
                                        id: 'Register'
                                    })
                                } else {
                                    that.props.navigator.push({
                                        id: 'MyRule'
                                    })
                                }
                            }
                            },
                            {text: '取消'}
                        ]
                    )
                } else if (responseData == 0) {
                    that.setState({
                        loaded: 2
                    })
                } else {
                    that.setState({
                        dataSource: that.state.dataSource.cloneWithRows(responseData),
                        loaded: 1,
                        loadMore: false
                    });
                }
                that._isFetching = false;
            })
        }
    }

    triggerModal() {
        this.setState({
            modalVisiable: true
        });
        this.setTimer = setTimeout(()=> {
            this.setState({
                modalVisiable: false
            })
        }, 1000);
    }


    _renderHeader() {
        return (
            <View style={styles.th}>
                <Text style={[styles.thText,{flex:2}]}>发布日期</Text>
                <Text style={[styles.thText,{flex:2}]}>股票代码</Text>
                <Text style={[styles.thText,{flex:2}]}>股票名称</Text>
            </View>
        );
    }

    handleEnd() {
        console.log("Ending!!!");
        var temp = this.state.pagesize;
        this.setState({
            loadMore: true,
            pagesize: this.state.pagesize + 10
        }, function cb() {
            this.fetchData()
        });
    }

    _renderFooter() {
        if (this.state.loadMore) {
            return (
                <View style={styles.footerload}>
                    <ActivityIndicatorIOS
                        animating={true}
                        style={{justifyContent:'center'}}
                    />
                    <Text>
                        加载数据...
                    </Text>
                </View>
            )
        }
    }

    renderNoData() {
        return (
            <View style={styles.container}>
                {
                    this.state.scroll!=''?
                    <ScrollNews content={this.state.scroll}/>:null
                }
                <View style={styles.navbar}>
                    <TouchableHighlight style={styles.navbar_side} onPress={()=>{this._forwardDay()}}>
                        <Text style={styles.navText}>前一天</Text>
                    </TouchableHighlight>
                    <View style={{flex:4}}>
                        <Text style={styles.navText}>
                            {formatDate2(this.state.showDate)}
                        </Text>
                    </View>
                    <TouchableHighlight style={styles.navbar_side} onPress={()=>{this._backwardDay()}}>
                        <Text style={styles.navText}>后一天</Text>
                    </TouchableHighlight>
                </View>
                <View style={styles.listView}>
                    <Text style={styles.centerText}>
                        暂无数据,请查询其他日期.
                    </Text>
                </View>
            </View>
        );
    }

    renderScene() {
        if (this.state.loaded == 0) {
            return this.renderLoadingView();
        } else if (this.state.loaded == 2) {
            return this.renderNoData();
        }
        return (
            <View ref="content" style={styles.container}>
                {
                    this.state.scroll!=''?
                    <ScrollNews content={this.state.scroll}/>:null
                }
                <View style={styles.navbar}>
                    <TouchableHighlight style={styles.navbar_side} onPress={()=>{this._forwardDay()}}>
                        <Text style={styles.navText}>前一天</Text>
                    </TouchableHighlight>
                    <View style={{flex:4}}>
                        <Text style={styles.navText}>
                            {formatDate2(this.state.showDate)}
                        </Text>
                    </View>
                    <TouchableHighlight style={styles.navbar_side} onPress={()=>{this._backwardDay()}}>
                        <Text style={styles.navText}>后一天</Text>
                    </TouchableHighlight>
                </View>
                <ListView
                    style={styles.contentView}
                    dataSource={this.state.dataSource}
                    renderRow={this.renderMovie.bind(this)}
                    renderHeader={this._renderHeader.bind(this)}
                    renderFooter={this._renderFooter.bind(this)}
                    renderSeparator={this._renderSeperator.bind(this)}
                />
                <Modal visible={this.state.modalVisiable} transparent={true}>
                    <View style={styles.modal}>
                        <Text style={{color:"#ffffff"}}>
                            正在刷新
                        </Text>
                    </View>
                </Modal>
                <TouchableOpacity style={styles.refresh} onPress={this._refresh.bind(this)} underColor="#ffffff">
                    <Animated.View style={{
                        transform: [
                        {rotate: this.state.angle.interpolate({
                          inputRange: [0, 360],
                          outputRange: ['0deg', '360deg']
                        })}]}}>
                        <Icon name="ios-refresh" size={40}
                              style={{height:40,width:40,alignSelf:'center',textAlign:'center'}}
                              color="#ffffff"/>
                    </Animated.View>
                </TouchableOpacity>

            </View>
        );
    }

    renderLoadingView() {
        return (
            <View style={styles.container}>
                {/*<ScrollNews marqueeText={this.state.scroll}/>*/}
                <View style={styles.listView}>
                    <Text style={styles.centerText}>
                        正在加载数据，请稍后...
                    </Text>
                </View>
            </View>
        );
    }

    renderMovie(data) {
        return (
            <TouchableOpacity onPress={()=>{console.log(data)}}>
                <View style={styles.Items}>
                    <Text style={this.state.isRed?styles.titleRed:styles.title}>{data.releaseTime}</Text>
                    <Text style={this.state.isRed?styles.titleRed:styles.title}>{data.stockCode}</Text>
                    <Text style={this.state.isRed?styles.titleRed:styles.title}>{data.stockName}</Text>
                </View>
            </TouchableOpacity>
        );
    }

    _renderSeperator(sectionID:number, rowID:number) {
        return (
            <View
                key={`${sectionID}-${rowID}`}
                style={{
          height: 1,
          backgroundColor: '#3B5998',
        }}
            />
        );
    }

    render() {
        return (
            <Navigator
                ref="main"
                renderScene={()=>this.renderScene()}
                navigator={this.props.navigator}
                message={this.props.message}
                navigationBar={navigationBar}
            />
        );
    }
}

var styles = StyleSheet.create({
    container: {
        marginTop: 64,
        flex: 1,
        backgroundColor: '#ffffff'
    },
    newstitle: {
        marginTop: 5,
        height: 30,
        width: 200
    },
    search: {
        flex: 1,
        justifyContent: 'center',
        paddingRight: 10
    },
    Items: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        padding: 10,
        backgroundColor: '#f5f5f9',
        borderBottomWidth: 0.5,
        borderColor: '#dddddd'
    },
    titleRed: {
        flex: 2,
        fontSize: 15,
        textAlign: 'center',
        color: '#ff0000'
    },
    footerload: {
        height: 30,
        justifyContent: 'center',
        alignItems: 'center',
        flexDirection: 'row'
    },
    contentView: {
        flex: 12,
        backgroundColor: '#f5f5f9'
    },
    listView: {
        flex: 12,
        paddingTop: 20,
        backgroundColor: '#f5f5f9',
        justifyContent: 'center',
        alignItems: 'center'
    },
    down: {
        flex: 1,
        backgroundColor: '#000000',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center'
    },
    bottomText: {
        flex: 1,
        color: '#ffffff',
        textAlign: 'center',
        fontSize: 16
    },
    rightContainer: {
        flex: 1,
        height: 70,
        justifyContent: 'flex-start'
    },
    title: {
        flex: 2,
        fontSize: 15,
        textAlign: 'center'
    },
    mtitle: {
        flex: 3,
        fontSize: 14,
        color: '#000000',
        textAlign: 'center'
    },
    thumbnail: {
        width: 100,
        height: 70,
        marginRight: 3,
        resizeMode: Image.resizeMode.stretch
    },
    searchBar: {
        marginTop: 64,
        padding: 3,
        paddingLeft: 8,
        flexDirection: 'row',
        alignItems: 'center'
    },
    searchBarInput: {
        fontSize: 15,
        flex: 1,
        height: 30
    },
    spinner: {
        width: 30
    },
    separator: {
        height: 1,
        backgroundColor: '#eeeeee'
    },
    refresh: {
        position: 'absolute',
        right: 10,
        bottom: 10,
        width: 44,
        height: 44,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 5,
        backgroundColor: 'rgba(0, 0, 0, 0.5)'
    },
    th: {
        flexDirection: 'row',
        backgroundColor: "#000000",
        height: 30,
        justifyContent: "center",
        alignItems: 'center'
    },
    thText: {
        flex: 1,
        borderRightWidth: 0.5,
        borderColor: '#dddddd',
        textAlign: 'center',
        fontSize: 16,
        color: '#ffffff'
    },
    navbar: {
        backgroundColor: '#292929',
        flexDirection: 'row',
        alignItems: 'center'
    },
    navbar_side: {
        backgroundColor: "#202020",
        width: 100,
        paddingBottom: 5,
        paddingTop: 5
    },
    navText: {
        textAlign: 'center',
        fontSize: 18,
        color: "#ffffff"
    },
    centerText: {
        fontSize: 18
    },
    modal: {
        position: 'absolute',
        bottom: 50,
        width: 80,
        height: 40,
        borderRadius: 5,
        justifyContent: 'center',
        alignItems: 'center',
        left: Utils.size.width / 2 - 40,
        backgroundColor: '#000000'
    }
});